//控制成品编码是否要进行触发事件：修改、拷贝第一次打开不触发
var costReportUpdateAndCoopyC=true;
//分辨率设置
getCostsystemFbl(systemFblW,systemFblH);
//dialog：查询
function costReportSelect(banben) {
    if (banben != null && banben != '') {
        var msg= commonAjax('GET','/costReportForm/getCostReportGrf',{"banben":banben});
        if (msg.status == 200) {
            window.open("/costReportForm/queryCostReportForm.html?banben=" + banben)
        }
        if (msg.status == 500) {
            layer.msg("没有相关数据!")
        }
    } else {
        commonTooltip($("#banbenTooltip"),"请先填写版本号!","top",'FF9999')
    }

}

//根据组织和权限判断是否有权限新增成本报告，2020年10月19要求 惠州澳宝的项目经理以上才可以编写成本报告
var user = getSessionUser();
costReportLimits(user.pkOrg,user.userPosition)
function costReportLimits(osg,post) {

    if (osg==window.OSG_HUIZHOU_CODE){
        if (post==window.POST_YUANGONG_CODE){
            $("#costReport_Add").hide();
            $("#costReport_copy").hide();
            $("#costReport_updata").hide();
            $("#costReport_delete").hide();
            $("#costReport_su").hide();
        }
    }

}

//dialog：新增成本报告表
function costReportAdd() {
    $("#costReport_dlg").dialog({
        width:costsystemFblW,
        height:costsystemFblH,
        title:'新增成本报告表',
        closed:false,
        href:'/costReportForm/costReportForm.html',
        buttons: costReportIndexButtons,
        onLoad:function(){
            costReportUserOutmoded()
            cost_report_a_reloadFooter();
            cost_report_b_count();
            cost_report_c_count();
            //生成版本号 获取本月数据库中最大版本号
            $.ajax({
                url: '/costReportForm/createGetcostReportId',
                success: function (data) {
                    $('#costReportId').textbox('setValue', data)
                }
            })
        },
        onClose:function () {
            //删除成本单据号：判断是否有未填写必填项的数据，若有进行删除
            var costRepordId=$('#costReportId').textbox('getValue');
            commonAjax("get", "/costReport/deleteFieldIsNullByCostReportId", {"costReportId":costRepordId})
            $("#costReport_Form_div").remove();
            //销毁提示框:运费关掉成本报告后，会残留这个提示框，再次打开又会多一个造成不能获取的问题
            $("#calculateFumigationChargeDiv").remove();
            $("#calculateCartonCertificateDiv").remove();
            $("#calculateFreightDiv").remove();
            $("#calculateCustoms_feeDiv").remove();
            $("#calculateOtherChargesDiv").remove();
            $('#fumigation_chargeDiv').remove();
            $('#carton_certificateDiv').remove();
        }
    })
    $('#costReport_dlg').dialog('center');
}

//dialog：修改
function costReportUpdata() {
    //由于成本编码会触发事件刷出所有的配件，设置了全局变量，让其第一次刷新不出数据
    costReportUpdateAndCoopyC=false;
    costReportUserOutmoded()
    var costReport;
    var banben = $("#banben").val();
    if (banben != '' && banben != null) {
        var msg = commonAjax('GET', '/costReport/isCostReportStatus', {"banben": banben});
        if (msg) {
            //1、审核完(全部同意)，2、审核中的两个状态不能进行修改
            var costReportStatus = msg.costReportStatus;
            if (costReportStatus!=1 && costReportStatus != 3){
                //必须是申请人才可以进行修改
                if(msg.userId ==$("#indexUserId").val()){
                    $("#costReport_dlg").dialog({
                        width:costsystemFblW,
                        height:costsystemFblH,
                        title:'修改成本报告表',
                        closed:false,
                        href:'/costReportForm/costReportForm.html',
                        buttons:costReportIndexButtons,
                        onLoad:function(){ //内容加载完后触发
                            $('#finishedProductCode').textbox('readonly', false);//成本编码更改为可修改
                            var data = commonAjax('GET', '/costReportForm/getCostReportABC', {"banben": banben});
                            costReport = data.table[0].costReport;
                            //产品图片
                            loadCostImage(costReport);
                            $('#costReport_Form').form('load', costReport);
                            //因为默认是给隐藏掉的成品编码赋值的，这里需要为id为：finishedProductCodeZt的进行赋值，
                            var finishedProductCodeZt= $("#finishedProductCodeZt");
                            if(finishedProductCodeZt){
                                $("#finishedProductCodeZt").textbox("setValue",costReport.finishedProductCode)
                            }
                            $("#cost_report_b").datagrid("loadData", data.table[0].b);
                            $("#cost_report_c").datagrid("loadData", data.table[0].c);
                            $("#cost_report_a").datagrid("loadData", data.table[0].a);
                            costReportBSinglehoursItem=data.table[0].bs;            //标准工时历史操作详情
                            calculateOtherChargesZtTableData=data.table[0].bo;      //授权费\顾问\其他历史操作详情
                            cartonTableData=data.table[0].ctd
                            cartonTableDataK=data.table[0].ctdk
                            cost_report_b_count();//B人工总价格
                            cost_report_c_count();//C配件费总价格
                            cost_report_a_reloadFooter(); //A 水料价格
                            oneUpdateShow(costReport.vatexportTaxRate);
                            $('#reality_quoted_price').numberbox('enable') //启用实际报价输入
                        },
                        onClose:function () {
                            $("#costReport_Form_div").remove();
                            //销毁提示框:运费关掉成本报告后，会残留这个提示框，再次打开又会多一个造成不能获取的问题
                            $("#calculateFumigationChargeDiv").remove();
                            $("#calculateCartonCertificateDiv").remove();
                            $("#calculateFreightDiv").remove();
                            $("#calculateCustoms_feeDiv").remove();
                            $("#calculateOtherChargesDiv").remove();
                            $('#fumigation_chargeDiv').remove();
                            $('#carton_certificateDiv').remove();
                        }
                    })
                    $('#costReport_dlg').dialog('center'); //窗口纠正居中
                }else {
                    layer.msg("您不是本次成本报告表的申请人，不能进行修改操作！")
                }
            }else {
                layer.msg("审核中或已封存的不能进行修改！")
            }
        } else {
            layer.msg("没有相关数据!")
        }
    } else {
        commonTooltip($("#banbenTooltip"),"请先填写版本号!","top","FF9999")
    }
}

//dialog：拷贝
function costReportCopy() {
    costReportUpdateAndCoopyC=false;
    costReportUserOutmoded()
    var costReport;
    var banben = $("#banben").val();
    if (banben != '' && banben != null) {
        var msg = commonAjax('GET', '/costReport/isCostReportStatus', {"banben": banben});
        if (!msg) {
            layer.msg("没有相关数据!")
        } else {
            $("#costReport_dlg").dialog({
                width: costsystemFblW,
                height: costsystemFblH,
                title: '拷贝成本报告表',
                closed: false,
                href: '/costReportForm/costReportForm.html',
                buttons: costReportIndexButtons,
                onLoad: function () {
                    $('#finishedProductCode').textbox('readonly', false);//成本编码更改为可修改
                    var data = commonAjax('GET', '/costReportForm/getCostReportABC', {
                        "banben": banben,
                        "copy": "true"
                    });//附带copy标识符后台去除id
                    costReport = data.table[0].costReport;
                    //去除产品图片路径
                    costReport.costImagePath=""
                    $('#costReport_Form').form('load', costReport);
                    //因为默认是给隐藏掉的成品编码赋值的，这里需要为id为：finishedProductCodeZt的进行赋值，
                    var finishedProductCodeZt= $("#finishedProductCodeZt");
                    if(finishedProductCodeZt){
                        $("#finishedProductCodeZt").textbox("setValue",costReport.finishedProductCode)
                    }
                    $("#cost_report_a").datagrid("loadData", data.table[0].a);
                    $("#cost_report_b").datagrid("loadData", data.table[0].b);
                    $('#cost_report_c').edatagrid('loadData', data.table[0].c)
                    costReportBSinglehoursItem=data.table[0].bs;
                    calculateOtherChargesZtTableData=data.table[0].bo;
                    cartonTableData=data.table[0].ctd
                    cartonTableDataK=data.table[0].ctdk
                    cost_report_b_count();//B人工总价格
                    cost_report_c_count();//C配件费总价格
                    cost_report_a_reloadFooter(); //A 水料价格
                    oneUpdateShow(costReport.vatexportTaxRate);
                    $('#reality_quoted_price').numberbox('enable') //启用实际报价输入
                    if (data.status == 200) {

                        //生成版本号 获取本月数据库中最大版本号
                        $.ajax({
                            url: '/costReportForm/createGetcostReportId',
                            success: function (data) {
                                $('#costReportId').textbox('setValue', data)
                            }
                        })
                    }
                    if (data.status == 500) {
                        topCommonMessage("没有相关数据!")
                    }

                },
                onClose: function () {
                    //判断是否有未填写必填项的数据，若有证明已放弃这次的成本报告操作
                    var costRepordId=$('#costReportId').textbox('getValue');
                    commonAjax("get", "/costReport/deleteFieldIsNullByCostReportId", {"costReportId":costRepordId})
                    $("#costReport_Form_div").remove();
                    //销毁提示框:运费关掉成本报告后，会残留这个提示框，再次打开又会多一个造成不能获取的问题
                    $("#calculateFumigationChargeDiv").remove();
                    $("#calculateCartonCertificateDiv").remove();
                    $("#calculateFreightDiv").remove();
                    $("#calculateCustoms_feeDiv").remove();
                    $("#calculateOtherChargesDiv").remove();
                    $('#fumigation_chargeDiv').remove();
                    $('#carton_certificateDiv').remove();
                }
            })
            $('#costReport_dlg').dialog('center'); //窗口纠正居中
        }
    } else {
        commonTooltip($("#banbenTooltip"),"请先填写版本号!","top",'A4E9C1')
    }
}

//删除
function costReportDelete() {
    var banben = $("#banben").val();
    if (banben != '' && banben != null) {
        var data = commonAjax('GET', '/costReport/deleteCostReport', {"costReportId": banben});
        if (data.status==200){
            //重新加载表格
            $('#costReportIndexTable').datagrid('reload');// 重新载入当前页面数据
        }
        layer.msg(data.msg)
    } else {
        commonTooltip($("#banbenTooltip"),"请先填写版本号!","top","FF9999")
    }
}

//停用/启用
function costReportSu() {
    var banben = $("#banben").val();
    if (banben != '' && banben != null) {
        var data = commonAjax('GET', '/costReport/SUCostReport', {"costReportId": banben});
        if (data.status==200){
            //重新加载表格
            $('#costReportIndexTable').datagrid('reload');// 重新载入当前页面数据
        }
        layer.msg(data.msg)
    } else {
        commonTooltip($("#banbenTooltip"),"请先填写版本号!","top","FF9999")
    }
}

//打印页面
function costReportPrint() {
    var banben = $("#banben").val();
    if (banben != '' && banben != null) {
            costReportSelect(banben);
    } else {
        commonTooltip($("#banbenTooltip"),"请先填写版本号!","top","FF9999")
    }

}


//成本报告导出excel
function costReportExcel() {
    var banben = $("#banben").val();
    if (banben != '' && banben != null) {
        var aDom = document.createElement('a')
        var evt = document.createEvent('HTMLEvents')
        evt.initEvent('click', false, false)
        aDom.download = name
        aDom.href = "/costReportForm/exportCostReportToExcel?costReportId="+banben;
        aDom.dispatchEvent(evt)
        aDom.click()
    } else {
        commonTooltip($("#banbenTooltip"),"请先填写版本号!","top","FF9999")
    }
}

//底层按钮数组
var costReportIndexButtons= [
    {
        id:"costReportIndexButtonsSaveAndAuditId",
        text: "保存并审核",
        iconCls: 'icon-ok',
        handler: function () {
            $(this).linkbutton('disable');
            costReport_save_audit($(this))
        }
    },{
        id:"costReportIndexButtonsSaveId",
        //disabled:"true",
        text: '保存',
        iconCls: 'icon-edit',
        handler: function () {
            $(this).linkbutton('disable');
            costReport_save($(this))
        }
    },
    {
        text: '取消',
        iconCls: 'icon-undo',
        handler: function () {
            $('#costReport_dlg').dialog('close')
        }
    }
]

//成本报告表:保存
function costReport_save(t) {

    if(finishedProductCode2Geshi){
        $('#costReport_Form').form('submit', {
            iframe:false,
            queryParams: costReportIndexSaveData(),
            url: "/costReport/costReportSave",
            onSubmit: function () {
                var isValid = $(this).form('validate');
                if (isValid){
                    var v=  $('#v_a_t_export_tax_rate').numberbox('getValue');
                    if (v==0){
                        layer.msg("T2税项未填写！")
                        isValid= false;
                    }
                    var v1=  $('#accessories_loss_rate').numberbox('getValue');
                    if (v1==0.00 || v1 ==""){
                        layer.msg("配件耗损率未填写！")
                        isValid=false;
                    }
                }

                if (!isValid){
                    //验证不成功打开保存按钮
                    $("#costReportIndexButtonsSaveId").linkbutton('enable');
                }
                return isValid;	// 返回false终止表单提交
            },
            success: function (data) {
                var data = eval('(' + data + ')');
                if (data.statu == 200) {
                    windowsOperation('costReport_dlg', null, data)
                    //重新加载表格
                    $('#costReportIndexTable').datagrid('reload');// 重新载入当前页面数据
                } else {
                    layer.msg(data.message)
                }
            },
            onLoadError: function (data) {
                layer.msg("服务器维护中")
            }
        });
    }else {
        $(t).linkbutton('enable');
        layer.msg("物料编码未填写正确")
    }

}

//成本报告表:保存并审核
function costReport_save_audit(t) {
    if(finishedProductCode2Geshi) { //要求物料编码2需要正确的填写，查询页面会造成查询不了
        $('#costReport_Form').form('submit', {
            iframe: false,
            queryParams: costReportIndexSaveData(),
            url: "/costReport/costReportSaveAudit",
            onSubmit: function () {

                var isValid = $(this).form('validate');

                if (isValid) {
                    var v = $('#v_a_t_export_tax_rate').numberbox('getValue');
                    if (v == 0) {
                        layer.msg("T2税项未填写！")
                        isValid = false;
                    }
                    var v1 = $('#accessories_loss_rate').numberbox('getValue');
                    if (v1 == 0.00 || v1 == "") {
                        layer.msg("配件耗损率未填写！")
                        isValid = false;
                    }
                }

                if (!isValid) {
                    //验证不成功打开保存按钮
                    $("#costReportIndexButtonsSaveAndAuditId").linkbutton('enable');
                }
                return isValid;	// 返回false终止表单提交
            },
            success: function (data) {
                var data = eval('(' + data + ')');
                if (data.statu == 200) {
                    windowsOperation('costReport_dlg', null, data)
                    //重新加载表格
                    $('#costReportIndexTable').datagrid('reload');// 重新载入当前页面数据
                } else {
                    layer.msg(data.message)
                }
            },
            onLoadError: function (data) {
                layer.msg("服务器维护中")
            }
        });
    }else {
        $(t).linkbutton('enable');
        layer.msg("物料编码未填写正确")
    }

}

function costReportUserOutmoded() {
    var costReportFormContent= $("#costReport_dlg").text();
    if(costReportFormContent.indexOf("登录已过期，请重新登录！}" >0)){
        costReportFormContent=  costReportFormContent.replace("401",404)
        sessionCloseDialog(costReportFormContent,$("#costReport_dlg"),'新增成本报告表');
    }
}

//--------------查询操作--------------------
var costReportIndexCostReportDate= $("#costReportIndexCostReportDate").datebox({
    editable:false,
    onSelect:function (date) {
        //月份
        var month=date.getMonth()+1;
        if (month<10){
            month="0"+month;
        }
        var day=date.getDate();
        if (day<10){
            day="0"+day;
        }
       var d= date.getFullYear()+"-"+month+"-"+day;
        costReportIndexQuery(d,"costReportDate")
    }

})

//成本单据
var costReportIndexCostReportId= $("#costReportIndexCostReportId").textbox({
    onChange:function (newValue,oldValue) {
        costReportIndexQuery()
    }
})

//成本编码
var costReportIndexCode= $("#costReportIndexCode").textbox({
    onChange:function (newValue,oldValue) {
        costReportIndexQuery()
    }
})
$(function () {
    costReportIndexQuery()
})

function costReportIndexQuery() {

    $("#costReportIndexTable").datagrid({
        idField:'costReportId',
        method:'post',
        url:'/costReport/pagingQueryCostReport',
       // updateUrl:'/costReport/updateQuotation',
        onBeforeLoad:function (param) { //使用此事件

            var t = $("#costReportIndexForm").serializeArray();
            t.forEach(function (val) {
                param[val.name]=val.value;
            })

        },
        onSave:function(index,row){
            if (row.msg){
                layer.msg(row.msg)
            }
            var status=row.status
            if (status){
                if (status.status !=200){
                    $("#costReportIndexTable").edatagrid("load")
                }
            }


        },
        onClickRow:function (index,row) {
            $("#banben").textbox("setValue",row.costReportId)
        }
    })

}
//格式化成本单据号
function costReportIndexCostReportIdformatter(value,row,index){
    return '<a  onclick="costReportIndexCostReportIdformatterBtnFun(this)" href="#">'+value+'</a>'
}

//点击表格中的成品编码查询
function costReportIndexCostReportIdformatterBtnFun(a) {
    $("#costReportIndexTable").before('<div id="costReport_dlg_selfTask2"></div>')
    var costReportId= a.innerHTML
    costReportQuery(costReportId)
}

function costReportQuery(banben) {
    $("#costReport_dlg_selfTask2").dialog({
        title:"成本报告表",
        width:costsystemFblW,
        height:costsystemFblH,
        closed:false,
        href:'/costReportForm/costReportFormStatic.html',
        buttons:[],
        onLoad:function(){ //内容加载完后触发
            var data = commonAjax('GET', '/costReportForm/getCostReportABC', {"banben": banben});
            costReport = data.table[0].costReport;
            //产品图片
            var costImagePath=costReport.costImagePath;
            if (costImagePath){
                $("#costReportFormImageStatic").show()   //显示img标签
                $("#costReportFormImageStatic").attr("src",costImagePath)  //赋值为img的src赋值
                $("#costImagePathDivStatic").hide();    //隐藏文字
            }
            $('#reportFormStatic_Form').form('load', costReport);
            $("#cost_report_static_a").datagrid("loadData", data.table[0].a);
            $("#cost_report_static_b").datagrid("loadData", data.table[0].b);
            $("#cost_report_static_c").datagrid("loadData", data.table[0].c);
            costReportBSinglehoursItem=data.table[0].bs;
        },
        onClose:function () {
            $("#costReport_dlg_selfTask2").remove();
        }
    })
    $('#costReport_dlg_selfTask2').dialog('center');
}

function costReportIndexcostReportStatusformatter(value,row,index) {
    //审核状态:0未审核 ,1审核通过 ,2审核不通过,3审核中
    switch (value) {
        case 0:
            return "<span style='color: #92B8B1'>未审核</span>"
            break;
        case 1:
            return "<span style='color: #704fa0'>审核完成</span>"
            break;
        case 2:
            return "<span style='color: #df0000'>拒绝</span>"
            break;
        case 3:
            return "<span style='color: #e68900'>审核中</span>"
            break;
    }
}
function costReportIndexcostReportCostReportStatus2(value,row,index) {
    //审核状态:0未审核 ,1审核通过 ,2审核不通过,3审核中
    switch (value) {
        case '正常':
            return "<span style='color: #92B8B1'>正常</span>"
            break;
        case '停用':
            return "<span style='color: red'>停用</span>"
            break;
    }
}

$("#costReportIndexUpdateQuotationDivUserName").textbox({
    onClickButton:function () {
        var userName=$("#costReportIndexUpdateQuotationDivUserName").textbox('getValue');

        //获取授权的用户id
        $("#costReportIndexUpdateQuotationInputUser").tree('loadData',commonAjax("get","/manage/user/selectalluserTree",{userName:userName}))
    }
})

//加载产品图片
function  loadCostImage(costReport) {
    var path=costReport.costImagePath;
    if (path){
        $("#costReportFormImageDiv").show()
        $("#costReportFormImage").attr("src",path+"?ran=" + Math.random())
        $("#costImagePathDiv").hide();
    }
}
